package com.seventh.associationsystem.controller;


import com.seventh.associationsystem.bean.HttpResult;
import com.seventh.associationsystem.bean.ResultCode;
import com.seventh.associationsystem.bean.Role;
import com.seventh.associationsystem.bean.User;
import com.seventh.associationsystem.service.RoleService;
import com.seventh.associationsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sys")
public class SystemController {

    public static int MIN_USERNAME = 6;

    public static int MAX_USERNAME = 16;

    public static int MIN_PASSWORD = 6;

    public static int MAX_PASSWORD = 16;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public HttpResult register(String username, String password, String retypePassword) {

        //TODO limit and verify
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return new HttpResult(ResultCode.USERNAME_EXIST_ERROR, "用户名已存在！");
        }
        if (password.compareTo(retypePassword) != 0) {
            return new HttpResult(ResultCode.PASSWORD_ERROR, "两次输入的密码不一致！");
        }
        User registerUser = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(new BCryptPasswordEncoder().encode(password));
        Role role = roleService.getRoleById(Role.ROLE_STUDENT);
        registerUser.addRole(role);
        userService.addUser(registerUser);
        return new HttpResult(ResultCode.NO_ERROR);
    }
}
